package api

import (
	"../utils"
	"net/url"
	"strconv"
	"encoding/json"
	"sync"
)

const doubanuri = "http://api.douban.com"

var (
	dbapi *douban
	once  sync.Once
)

type page struct {
	Count int `json:"count"`
	Start int `json:"start"`
	Total int `json:"total"`
}

type rate struct {
	Max     int     `json:"max"`
	Average float64 `json:"average"`
	Stars   string  `json:"stars"`
	Min     int     `json:"min"`
}

type movie struct {
	Id           string   `json:"id"`
	Title        string   `json:"title"`
	OrgTitle     string   `json:"original_title"`
	Rating       rate     `json:"rating"`
	CollectCount int      `json:"collect_count"`
	Year         string   `json:"year"`
	Genres       []string `json:"genres"`
}

type moviesResult struct {
	page
	Movies []movie `json:"subjects"`
}

type douban struct {
}

func NewDouBan() *douban {
	once.Do(func() {
		dbapi = &douban{}
	})
	return dbapi
}

func (d *douban) Search(keyword string, start, limit int) (*moviesResult, error) {
	u := doubanuri + "/v2/movie/search?q=" + url.QueryEscape(keyword) + "&start=" + strconv.Itoa(start) + "&count=" + strconv.Itoa(limit)
	buf, err := utils.NewHttpClient().Get(u)
	if err != nil {
		return nil, err
	}
	result := &moviesResult{}
	err = json.Unmarshal(buf, result)
	if err != nil {
		return nil, err
	}
	return result, nil
}
